package com.lixueju.security.box.core.dto;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lixueju.security.box.core.enums.ResultDataEnum;
import com.lixueju.security.box.core.exception.SecurityBoxException;
import com.lixueju.security.box.core.model.dto.UserToken;
import com.lixueju.security.box.core.properties.SecurityBoxProperties;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author lixueju
 * @since 2019/11/15 11:14
 **/
@Component
public class SecurityBoxUtils {

    @Autowired
    private SecurityBoxProperties securityBoxProperties;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private ObjectMapper objectMapper;

    public void writeFail(HttpServletResponse response, String message) {
        response.setContentType("application/json;charset=UTF-8");
        try {
            response.getWriter().write(objectMapper.writeValueAsString(new ResultData<>(ResultDataEnum.FAIL.code(), message, null)));
        } catch (IOException e) {
            e.printStackTrace();
            throw new SecurityBoxException("SecurityBoxUtils.writeFail异常");
        }
    }

    public void write(HttpServletResponse response, Integer code, String message) {
        response.setContentType("application/json;charset=UTF-8");
        try {
            response.getWriter().write(objectMapper.writeValueAsString(new ResultData<>(code, message, null)));
        } catch (IOException e) {
            e.printStackTrace();
            throw new SecurityBoxException("SecurityBoxUtils.write异常");
        }
    }

    public void writeSuccess(HttpServletResponse response, String message) {
        response.setContentType("application/json;charset=UTF-8");
        try {
            response.getWriter().write(objectMapper.writeValueAsString(new ResultData<>(ResultDataEnum.SUCCESS.code(), message, null)));
        } catch (IOException e) {
            e.printStackTrace();
            throw new SecurityBoxException("SecurityBoxUtils.writeSuccess异常");
        }
    }

    /**
     * 获取当前登录用户
     */
    public UserToken getUserToken(String token) {
        JSONObject jwtToken = getJwtToken(token);
        if (jwtToken == null) {
            return null;
        }
        return jwtToken.getObject("userToken", UserToken.class);
    }

    /**
     * 删除当前用户登录Token
     */
    public Boolean deleteUserToken(String token) {
        String key = securityBoxProperties.getClient().getTokenPrefix() + token;
        stringRedisTemplate.delete(key);
        return true;
    }

    /**
     * 获取jwt令牌字符串
     */
    public String getJwtTokenStr(String token) {
        JSONObject jwtToken = getJwtToken(token);
        if (jwtToken == null) {
            return null;
        }
        return jwtToken.getString("jwtToken");
    }

    public JSONObject getJwtToken(String token) {
        if (StringUtils.isBlank(token)) {
            return null;
        }
        String jwtUserString = stringRedisTemplate.opsForValue().get(securityBoxProperties.getClient().getTokenPrefix() + token);
        if (StringUtils.isBlank(jwtUserString)) {
            return null;
        }
        return JSONObject.parseObject(jwtUserString);
    }

    public boolean reSetJwtToken(String token, String jwtTokenStr) {
        String key = securityBoxProperties.getClient().getTokenPrefix() + token;
        Long expire = stringRedisTemplate.getExpire(key, TimeUnit.SECONDS);
        if (expire < 0) {
            return false;
        }
        stringRedisTemplate.boundValueOps(key).set(jwtTokenStr, expire, TimeUnit.SECONDS);
        Long reExpire = stringRedisTemplate.getExpire(key, TimeUnit.SECONDS);
        return reExpire > 0;
    }

}
